package autocode;

import com.celesea.workflow.core.entity.WorkflowPermission;
import com.celesea.workflow.demo.entity.Demo;
import com.celesea.workflow.demo.entity.DemoPerm;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import javax.persistence.Column;
import javax.persistence.Table;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class CreateTable {
    public static final Map<Class, String> TYPE = Maps.newHashMap();

    static {
        TYPE.put(String.class, "VARCHAR(%s)");
        TYPE.put(Integer.class, "int(11)");
        TYPE.put(Long.class, "bigint(20)");
        TYPE.put(Double.class, "double");
        TYPE.put(Float.class, "float(11,2)");
        TYPE.put(Date.class, "timestamp");
        TYPE.put(Byte.class, "bit(1)");
    }

    public static void main(String[] args) {
        // 类路径

        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println(getCreateSQL(Demo.class));
        System.out.println(getCreateSQL(DemoPerm.class));
//        System.out.println(getCreateSQL(WorkflowDefine.class));
//        System.out.println(getCreateSQL(WorkflowPermission.class));
//        System.out.println(getCreateSQL(WorkflowNode.class));
//        System.out.println(getCreateSQL(WorkflowNodeAction.class));
//        System.out.println(getCreateSQL(WorkflowNodePermission.class));
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();

    }

    @SuppressWarnings("unused")
    public static String getCreateSQL(Class<?> clazz) {
        // 加载类
        Class<?> c = clazz;
        // 获得指定类型的注解对象
        Table table = clazz.getAnnotation(Table.class);
        if (table == null) {
            return null;
        }
        String tableName = table.name();
        if (tableName.length() == 0) {
            // 如果没指定长度， 可以默认以类的名字 命名表名
            tableName = c.getName().toUpperCase();
        }
        List<String> columns = new ArrayList<String>();

        List<Field> fields = Lists.newArrayList(c.getDeclaredFields());
        c = c.getSuperclass();
        fields.addAll(0, Lists.newArrayList(c.getDeclaredFields()));
        c = c.getSuperclass();
        fields.addAll(0, Lists.newArrayList(c.getDeclaredFields()));
        try {
            c = c.getSuperclass();
            fields.addAll(0, Lists.newArrayList(c.getDeclaredFields()));
        } catch (Exception e) {
        }
        // columns.add("`id`  varchar(50) NOT NULL");
        // columns.add("`version`  int(11) NULL");
        // 遍历所有字段
        for (Field field : fields) {
            String columnName = null;
            String columnType = null;
            // 获得每个字段上的注解信息,这里不需要继承的注解
            // 还有其他方法，具体可以去看API
            Column col = field.getAnnotation(Column.class);
            if (col != null) {
                // 如果该字段没有注解，表示这个字段，不需要生成
                // 获得该字段的注解信息,默认这设置的column注解信息
                // 获得建表 语句 字符串
                String name = col.name();
                if (!TYPE.containsKey(field.getType())) {
                    System.err.println("不存在的类型:" + field.getType());
                    continue;
                }
                String type = TYPE.get(field.getType());
                boolean timestamp = type == "timestamp";
                Integer length = col.length();
                type = String.format(type, length);
                if (col.nullable()) {
                    type = type + " NULL";
                } else {
                    type = type + " NOT NULL";
                }
                if (timestamp) {
                    type = type + " DEFAULT CURRENT_TIMESTAMP ";
                }
                String constraint = "";
                if (name.length() == 0) {
                    // 获得默认字段名
                    columnName = field.getName();
                } else {
                    columnName = name;
                }

                columns.add(columnName + " " + type + " " + "COMMENT '" + col.columnDefinition() + "'");
            }
        }
        if (columns.size() == 0) {
            throw new RuntimeException("There is no field in " + c.getName());
        }
        StringBuilder createCommand = new StringBuilder("DROP TABLE IF EXISTS `" + tableName + "`; CREATE TABLE`" + tableName + "` (");
        for (String column : columns) {
            createCommand.append("\n " + column + " ,");
        }
        createCommand.append("\n PRIMARY KEY (`id`) ");
        String createTable = createCommand.substring(0, createCommand.length() - 1) + " \n ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
        return createTable;
    }

    // /**
    // * 获得约束条件
    // *
    // * @param con
    // * @return
    // */
    // private static String getConstraints(Constraints con) {
    // String constraints = "";
    // if (!con.allowNull()) {
    // constraints += " NOT NULL";
    // }
    // if (con.primaryKey()) {
    // constraints += " PRIMARY KEY";
    // }
    // if (con.unique()) {
    // constraints += " UNIQUE ";
    // }
    // return constraints;
    // }

    /**
     * 获得所需要的字段
     *
     * @param fields
     * @return
     */
    public static List<Field> getNeedField(Field[] fields) {
        List<Field> allFileds = new ArrayList<Field>();
        for (Field field : fields) {
            // 获得每个字段上的注解信息,这里不需要继承的注解
            Annotation[] anns = field.getDeclaredAnnotations();
            if (anns.length != 0) {
                // 如果该字段没有注解，表示这个字段，不需要生成
                allFileds.add(field);
            }
        }
        return allFileds;
    }
}